<template>
  <div class="attendance-container">
    <h1>学生考勤打卡</h1>
    
    <!-- 显示当前用户信息 -->
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }} (学生)</p>
      <router-link to="/student/dashboard">返回Dashboard</router-link>
    </div>

    <div class="clock-section">
      <h2>考勤打卡</h2>
      <div class="clock-buttons">
        <button @click="clockInMorning" :disabled="morningDisabled" class="clock-in-btn">
          早上签到
        </button>
        <button @click="clockOutAfternoon" :disabled="afternoonDisabled" class="clock-out-btn">
          下午签退
        </button>
      </div>
    </div>

    <div class="leave-section">
      <h2>请假申请</h2>
      <form @submit.prevent="submitLeave">
        <div class="form-group">
          <label for="leaveDate">请假日期:</label>
          <input type="date" id="leaveDate" v-model="leaveForm.leaveDate" />
        </div>
        <div class="form-group">
          <label for="verificationCode">请假验证码:</label>
          <input type="text" id="verificationCode" v-model="leaveForm.verificationCode" required />
        </div>
        <button type="submit" class="leave-btn">提交请假</button>
      </form>
    </div>

    <div class="records-section">
      <h2>我的考勤记录</h2>
      <button @click="loadAttendanceRecords" class="refresh-btn">刷新记录</button>
      <table class="records-table">
        <thead>
          <tr>
            <th>日期</th>
            <th>状态</th>
            <th>签到时间</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="record in attendanceRecords" :key="record.id">
            <td>{{ formatDate(record.recordDate) }}</td>
            <td>{{ getAttendanceStatusText(record.status) }}</td>
            <td>{{ formatDateTime(record.recordedAt) }}</td>
            <td>{{ record.remarks || '无' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <!-- 成功提示 -->
    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'StudentAttendance',
  setup() {
    // 用户信息
    const userProfile = ref({});
    
    // 考勤记录
    const attendanceRecords = ref([]);
    
    // 请假表单
    const leaveForm = ref({
      leaveDate: '',
      verificationCode: ''
    });
    
    // 状态信息
    const error = ref('');
    const success = ref('');
    const morningDisabled = ref(false);
    const afternoonDisabled = ref(false);

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取考勤记录
    const loadAttendanceRecords = async () => {
      if (!userProfile.value || !userProfile.value.id) return;
      
      try {
        const response = await fetch(`/attendance/record?studentId=${userProfile.value.id}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          attendanceRecords.value = result.data;
        } else {
          error.value = result.msg || '获取考勤记录失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 早上签到
    const clockInMorning = async () => {
      try {
        const response = await fetch('/attendance/clock-in-morning', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `studentId=${userProfile.value.id}`
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '签到成功';
          morningDisabled.value = true;
          // 重新加载考勤记录
          setTimeout(loadAttendanceRecords, 1000);
        } else {
          error.value = result.msg || '签到失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 下午签退
    const clockOutAfternoon = async () => {
      try {
        const response = await fetch('/attendance/clock-out-afternoon', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `studentId=${userProfile.value.id}`
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '签退成功';
          afternoonDisabled.value = true;
          // 重新加载考勤记录
          setTimeout(loadAttendanceRecords, 1000);
        } else {
          error.value = result.msg || '签退失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 提交请假申请
    const submitLeave = async () => {
      try {
        const params = new URLSearchParams();
        params.append('studentId', userProfile.value.id);
        params.append('verificationCode', leaveForm.value.verificationCode);
        if (leaveForm.value.leaveDate) {
          params.append('leaveDate', leaveForm.value.leaveDate);
        }
        
        const response = await fetch('/attendance/leave', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: params
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '请假申请提交成功';
          leaveForm.value.verificationCode = '';
          // 重新加载考勤记录
          setTimeout(loadAttendanceRecords, 1000);
        } else {
          error.value = result.msg || '请假申请提交失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取考勤状态文本
    const getAttendanceStatusText = (status) => {
      switch (status) {
        case '1': return '出勤';
        case '2': return '缺勤';
        case '3': return '迟到';
        case '4': return '请假';
        case '5': return '早退';
        default: return '未知';
      }
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    };

    // 格式化日期时间
    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '';
      const date = new Date(dateTimeString);
      return date.toLocaleString('zh-CN');
    };

    // 初始化
    onMounted(async () => {
      await loadUserProfile();
      await loadAttendanceRecords();
    });

    return {
      userProfile,
      attendanceRecords,
      leaveForm,
      error,
      success,
      morningDisabled,
      afternoonDisabled,
      loadAttendanceRecords,
      clockInMorning,
      clockOutAfternoon,
      submitLeave,
      getAttendanceStatusText,
      formatDate,
      formatDateTime
    };
  }
};
</script>

<style scoped>
.attendance-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.clock-section, .leave-section, .records-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.clock-buttons {
  display: flex;
  gap: 15px;
}

.clock-in-btn, .clock-out-btn, .leave-btn, .refresh-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.clock-in-btn {
  background-color: #4CAF50;
  color: white;
}

.clock-out-btn {
  background-color: #2196F3;
  color: white;
}

.leave-btn {
  background-color: #FF9800;
  color: white;
}

.refresh-btn {
  background-color: #9E9E9E;
  color: white;
  float: right;
  margin-bottom: 10px;
}

.clock-in-btn:disabled, .clock-out-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.records-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.records-table th, .records-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.records-table th {
  background-color: #f2f2f2;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}
</style>